import {
  collectByIdAPI,
  followByIdAPI,
  getArticlesByIdAPI,
  getDetailByIdAPI,
} from '@/api/article';
import { Toast } from 'antd-mobile';
import store, { AppDispatch } from '..';
import { ActionType } from '../reducer/article';
import {
  disfollowByIdAPI,
  disLikeByIdAPI,
  likeByIdAPI,
  disCollectByIdAPI,
} from './../../api/article';
export const getArticlesByIdAction = (channel_id: number, timestamp: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticlesByIdAPI(channel_id, timestamp);
    dispatch({
      type: 'article/saveList',
      payload: {
        channel_id,
        article: res.data,
      },
    });
  };
};

export const updateArticleByIdAction = (channel_id: number, timestamp: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticlesByIdAPI(channel_id, timestamp);
    dispatch({ type: 'article/updateList', payload: { channel_id, article: res.data } });
  };
};

export const getDetailByIdAction = (id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getDetailByIdAPI(id);
    dispatch({ type: 'article/saveDetial', payload: res.data });
  };
};

export const clearDetailAction = (): ActionType => ({
  type: 'article/saveDetial',
  payload: {} as any,
});

export const followByIdAction = (id: string) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const { is_followed } = getState().article.detail;
    if (is_followed) {
      await disfollowByIdAPI(id);
    } else {
      await followByIdAPI(id);
    }
    Toast.show({ content: is_followed ? '取消成功' : '关注成功' });
  };
};

export const likeByIdAction = (id: string) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const { attitude } = getState().article.detail;
    if (attitude === 1) {
      await disLikeByIdAPI(id);
    } else {
      await likeByIdAPI(id);
    }
    Toast.show({ content: attitude === 1 ? '取消成功' : '点赞成功', icon: 'success' });
  };
};

export const collectByIdAction = (id: string) => {
  return async (dispatch: AppDispatch, getState: typeof store.getState) => {
    const { is_collected } = getState().article.detail;
    if (is_collected) {
      await disCollectByIdAPI(id);
    } else {
      await collectByIdAPI(id);
    }
    Toast.show({ content: is_collected ? '取消收藏' : '收藏成功' });
  };
};
